package com.ocelot.san.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.icefaces.ace.model.table.SortCriteria;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import com.ocelot.san.dto.Lawyer;
import com.ocelot.san.dto.Notary;
import com.ocelot.san.dto.Operation;
import com.ocelot.san.dto.OperationType;
import com.ocelot.san.repository.LawyerRepository;
import com.ocelot.san.repository.NotaryRepository;
import com.ocelot.san.repository.OperationRepository;
import com.ocelot.san.repository.OperationTypeRepository;


@Service
public class OperationService {
	
	@Resource
	private OperationRepository operationRepository;
	
	@Resource
	private LawyerRepository lawyerRepository;

	@Resource
	private NotaryRepository notaryRepository;

	@Resource
	private OperationTypeRepository operationTypeRepository;


	public void save(Operation operation) {
		operationRepository.save(operation);
	}
	
	public List<Lawyer> fetchAllLawyers() {
		return lawyerRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
	}

	public List<OperationType> fetchAllOperationTypes() {
		return operationTypeRepository.findAll(new Sort(Sort.Direction.ASC, "description"));
	}
	
	public List<Notary> fetchAllNotaries() {
		return notaryRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
	}
	
	public List<Operation> fetchAllOperations() {
		return operationRepository.findAll(new Sort(Sort.Direction.ASC, "operationType.description"));
	}
	
	public Page<Operation> fetchAllOperationsWithPage(int currentPage, int size, SortCriteria[] sortCriteria) {
		Sort sort  = getSortFromSortCriteria(sortCriteria);
		Pageable pageable =  new PageRequest(currentPage, size, sort);
		return operationRepository.findAll(pageable);
	}
	
	public Sort getSortFromSortCriteria(SortCriteria[] sortCriterias) {
		Sort sort = null;
		if(sortCriterias!=null && sortCriterias.length > 0) {
			List<Order> orders = new ArrayList<Order>();
			for(SortCriteria criteria : sortCriterias) {
				Direction direction =  criteria.isAscending() ? Direction.ASC : Direction.DESC;
				orders.add(new Order(direction, criteria.getPropertyName()));
			}
			sort = new Sort(orders);
		}
		return sort;
	}
	

	public Lawyer findLawyerById(Long id) {
		return lawyerRepository.findOne(id);
	}	
	
	public OperationType findOperationTypeById(Long id) {
		return operationTypeRepository.findOne(id);
	}	
	
	public Notary findNotaryById(Long id) {
		return notaryRepository.findOne(id);
	}
	
	public Operation findOperationById(Long id) {
		return operationRepository.findOne(id);
	}

	
}
